import type { CAC } from 'cac';
import { execaCommand } from 'execa';

interface LintCommandOptions {
    format?: boolean;
}

async function runLint({ format }: LintCommandOptions) {
    if (format) {
        try {
            await execaCommand(`eslint . --cache --fix`, {
                stdio: 'inherit'
            });
        } catch (err) {}
        try {
            await execaCommand(`prettier . --write --cache --log-level warn`, {
                stdio: 'inherit'
            });
        } catch (err) {}
        try {
            await execaCommand(`stylelint "**/*.{vue,css,less,scss}" --cache --fix`, {
                stdio: 'inherit'
            });
        } catch (err) {}
    } else {
        execaCommand(`eslint . --cache`, {
            stdio: 'inherit'
        });
        execaCommand(`prettier . --ignore-unknown --check --cache`, {
            stdio: 'inherit'
        });
        execaCommand(`stylelint "**/*.{vue,css,less,scss}" --cache`, {
            stdio: 'inherit'
        });
    }
}

export function defineLintCommand(cac: CAC) {
    cac.command('lint')
        .usage('Batch execute project lint check.')
        .option('--format', 'Format lint problem.')
        .action(runLint);
}
